import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  TouchableOpacity,
  StatusBar,
  Platform
} from 'react-native';
import { API, API_GENERATE } from '../../config/api';
import StorageHelper from '../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../config/storage';
import { GLOBAL } from '../../config/global';
import ToastUtil from '../../utils/toast';
import HTTP from '../../utils/http';
import Dictionary from '../../utils/dictionary';
import Permission from '../../utils/permission';
import TouchID from 'react-native-touch-id';

const appInfo = require('react-native-device-info');
const touchIDImg = require('../../imgs/img-touchid.png');
const faceIDImg = require('../../imgs/img-faceid.png');
const logoIcon = require('../../imgs/logoIng.png');
const scale = GLOBAL.SCALE;

export class AuthenticationPages extends Component {
  static navigationOptions = {
    header: null,
    gesturesEnabled: false //禁止侧滑返回事件
  }


  requesting;

  constructor(props) {
    super(props);
    this.state = {
      status: 'data',
    };
    this.loginInfo = {
      loginName: '',
      password: ''
    }
  }

  async componentDidMount () {
    let { params } = this.props.navigation.state;
    this.params = params;
    if (this.params.autoLogin && this.params.username && this.params.password) {
      //开启指纹识别
      this.authenticate()
    }
  }

  authenticate = async () => {
    //开启指纹识别
    TouchID.authenticate('指纹/人脸识别登录', {
      title: '通过识别键验证',
      imageColor: '#e00606',
      imageErrorColor: '#ff0000',
      sensorDescription: '请放入手指识别',
      sensorErrorDescription: '识别失败，请重试',
      unifiedErrors: true,
      fallbackLabel: '账号登录',
      cancelText: '取消',
      passcodeFallback: false,
    }).then(success => {
      this.setState({
        status: 'loading'
      })
      let { params } = this.props.navigation.state;
      this.loginInfo.loginName = params.username;
      this.loginInfo.password = params.password;
      if (success) {
        this.setState({
          status: 'data'
        }, () => {
          GLOBAL.BIND_LOGIN_TYPE = 'BIOMETRY'
          StorageHelper.set(STORAGE_CONSTANT.BIND_LOGIN_TYPE, GLOBAL.BIND_LOGIN_TYPE);
          this.login();
        });
      }

    }).catch(error => {
      console.log(error.code)
      if (error.code === 'UNKNOWN_ERROR') {
        ToastUtil.showWarning('出现未知错误,请手动登录');
      }
    });

  }

  // 登录
  async login () {
    if (this.requesting) return;
    this.loginInfo.devCode = appInfo.getUniqueID();
    this.setState({
      status: 'loading'
    })
    this.requesting = true;
    let loginResult = await HTTP.POST(API_GENERATE(API.DO_LOGIN), this.loginInfo);
    if (loginResult) {
      if (loginResult.pwdReset === 1) {
        GLOBAL.pwdReset = true;
        this.requesting = false;
        this.props.navigation.navigate('SetPassWordPage', { resetPwdToken: loginResult.token, pwdReset: true });
      } else {
        let userInfo = loginResult;
        await this.saveUserInfo(userInfo);
      }
    } else {
      this.requesting = false;
    }
    this.setState({
      status: 'data'
    })
  }
  // 跳转登入
  goLogin = async () => {
    this.props.navigation.navigate('LoginPage')
  }


  async saveUserInfo (userInfo) {
    GLOBAL.TOKEN = userInfo.authToken;
    GLOBAL.LOGIN_NAME = userInfo.loginName;
    this._registerJPush();
    Promise.all([
      Dictionary.init(),
      Permission.init(),
      StorageHelper.multiSet([
        [STORAGE_CONSTANT.USER_INFO_KEY, userInfo],
        [STORAGE_CONSTANT.TOKEN, userInfo.authToken],
        [STORAGE_CONSTANT.LOGIN_ACCOUNT_KEY, this.loginInfo.loginName],
      ])
    ]).then(() => {
      ToastUtil.showSuccess('登录成功').then(async () => {
        GLOBAL.CURR_MODULE = '2.0';
        this.requesting = false;
        this.props.navigation.navigate('Layout');
      })
    })
  }

  async _registerJPush () {
    let APP_HOT_VERSION = await StorageHelper.get(STORAGE_CONSTANT.APP_HOT_VERSION);
    //极光推送
    if (!appInfo.isEmulator()) {
      let registrationId = await StorageHelper.get(STORAGE_CONSTANT.REGISTRATION_ID);
      await HTTP.POST(API_GENERATE(API.PUSH_REGISTER_INFO), {
        appVersion: appInfo.getVersion(),
        deviceCode: appInfo.getUniqueID(),
        deviceType: Platform.OS.substring(0, 1),
        osVersion: appInfo.getSystemVersion(),
        phoneBrand: appInfo.getModel(),
        phoneModel: appInfo.getModel(),
        registrationId: registrationId,
        extVersionCode: APP_HOT_VERSION
      });
    }
  }

  render () {
    let authType = GLOBAL.SUPPORT_BIOMETRY_TYPE === 'FaceID' ? 'FaceID' : 'TouchID'
    console.log(authType)
    return (
      <View style={styles.container}>
        <StatusBar
          backgroundColor='#fff'
          barStyle="default"
        />
        {/* <TouchableOpacity onPress={this.authenticate}>
          <Text style={styles.welcome}>
            指纹/人脸登录
						</Text>
        </TouchableOpacity> */}
        <View style={styles.itemBox}>
          <Image style={styles.itemBoxIcon} source={logoIcon} />
        </View>

        <TouchableOpacity style={styles.flexNum} onPress={this.authenticate}>
          <View style={styles.flexItem}>
            <Image style={styles.flexItemIcon} source={authType === 'FaceID' ? faceIDImg : touchIDImg} />
          </View>
          <View style={styles.flexItem}>
            <Text style={styles.flexItemText}>点击进行指纹解锁登入</Text>
          </View>
        </TouchableOpacity>

        <TouchableOpacity style={styles.flexBtn} onPress={this.goLogin}>
          <Text style={styles.flexBtnText}>登入其它账户</Text>
        </TouchableOpacity>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    height: '100%',
    backgroundColor: '#fff',
    alignItems: 'center',
  },
  itemBox: {
    flexDirection: 'row',
    justifyContent: 'center',
    paddingTop: 40 * scale,
    paddingBottom: 110 * scale,
  },
  itemBoxIcon: {
    width: 120 * scale,
    height: 120 * scale,
  },
  flexNum: {
    // marginTop: 120 * scale,
    // flex: 1,
    flex: 1,
  },
  flexItem: {
    flexDirection: 'row',
    justifyContent: 'center',
  },
  flexItemIcon: {
    width: 60 * scale,
    height: 60 * scale,
    backgroundColor: '#fff',
  },
  flexItemText: {
    paddingTop: 16 * scale,
    color: '#459df5',
    // flexDirection: 'row',
    // justifyContent: 'center',
  },
  flexBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingBottom: 30 * scale,
  },
  flexBtnText: {
    color: '#459df5',
  },
})
